import { GeneraDataType } from "@/interface";
import { Form } from "ant-design-vue";
import { ref } from "vue";
export default function FormHook(state: GeneraDataType = {}) {
  const { formState } = state;
  const useForm = Form.useForm;
  const { resetFields } = useForm(formState, ref<any>({}));
  // 不允许输入中文
  const validateZhInputHandle = (e: any, target: GeneraDataType, keys: Array<string>) => {
    keys.reduce((a: any, b: any, i: number) => {
      if (i === keys.length - 1) a[b] = e.target.value.replace(/[\u4E00-\u9FA5]/g, "");
      else return a[b];
    }, target);
  };
  const filterOption = (input: string, option: any) => {
    return String(option.label).toLowerCase().indexOf(String(input).toLowerCase()) >= 0;
  };
  // 只允许输入正整数
  const validateIntergeHandle = (e: any, target: Base.GeneraDataType, keys: Array<string>) => {
    keys.reduce((a: any, b: any, i: number) => {
      if (i === keys.length - 1) a[b] = e.target.value.replace(/\D|(^0+(?=\d))/g, "");
      else return a[b];
    }, target);
  };
  // 只允许输入英文
  const validateEnHandle = (e: any, target: Base.GeneraDataType, keys: Array<string>) => {
    keys.reduce((a: any, b: any, i: number) => {
      if (i === keys.length - 1) a[b] = e.target.value.replace(/[^a-zA-Z]/g, "");
      else return a[b];
    }, target);
  };

  // 纯数字
  const validatePhoneInputHandle = (e: any, target: GeneraDataType, keys: Array<string>) => {
    keys.reduce((a: any, b: any, i: number) => {
      if (i === keys.length - 1) a[b] = e.target.value.replace(/[^0-9]/g, "");
      else return a[b];
    }, target);
  };

  const initValueToUndefined = <T>(target: T): T => {
    for (const key in target) {
      if (!target[key]) (target as any)[key] = undefined;
    }
    return target;
  };
  return {
    resetFields,
    validateZhInputHandle,
    filterOption,
    validateIntergeHandle,
    initValueToUndefined,
    validateEnHandle,
    validatePhoneInputHandle
  };
}
